package com.kmproject.haifu.mvp.ui.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.jess.arms.base.AdapterViewPager;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.integration.AppManager;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.DataHelper;
import com.jess.arms.widget.alertview.AlertView;
import com.jess.arms.widget.alertview.AlertViewOnItemClickListener;
import com.kmproject.haifu.R;
import com.kmproject.haifu.app.AppConstant;
import com.kmproject.haifu.app.receiver.TagAliasOperatorHelper;
import com.kmproject.haifu.app.service.HfLocationService;
import com.kmproject.haifu.app.utils.AppUtil;
import com.kmproject.haifu.app.utils.DataCleanManager;
import com.kmproject.haifu.app.utils.NoticeisUtils;
import com.kmproject.haifu.di.component.DaggerHomeComponent;
import com.kmproject.haifu.mvp.contract.HomeContract;
import com.kmproject.haifu.mvp.model.entity.beans.UserBean;
import com.kmproject.haifu.mvp.presenter.HomePresenter;
import com.kmproject.haifu.mvp.ui.fragment.HfMeFragment;
import com.kmproject.haifu.mvp.ui.fragment.HomeFindFragment;
import com.kmproject.haifu.mvp.ui.fragment.HomeMainFragment;
import com.kmproject.haifu.mvp.ui.widget.HomeBottomBar;
import com.kmproject.haifu.mvp.ui.widget.NoScrollViewPager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.jess.arms.utils.DataHelper.getDeviceData;
import static com.jess.arms.utils.Preconditions.checkNotNull;
import static com.kmproject.haifu.app.receiver.TagAliasOperatorHelper.ACTION_SET;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 07/08/2019 23:39
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class HomeActivity extends BaseActivity<HomePresenter> implements HomeContract.View {

    @BindView(R.id.home_fragment_view_page)
    NoScrollViewPager homeFragmentViewPage;
    @BindView(R.id.bottom_bar)
    HomeBottomBar bottom_bar;
    private long exitTime = 0;
    private List<Fragment> fragments;
    private int defaultIndex = 0;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerHomeComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_home; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(Bundle savedInstanceState) {
      if (!NoticeisUtils.isPermissionOpen(this))
      {
          if (DataHelper.getBooleanSF(this,AppConstant.user_OPEN_NOTICE))
          {
              //没开启通知权限，提示开启
              new AlertView("提示", "确定要清除缓存？", "取消", new String[]{"确定"}, null, this, AlertView.Style.Alert, new AlertViewOnItemClickListener() {

                  @Override
                  public void onItemClick(Object o, int position) {
                      if (position == AlertView.CANCELPOSITION) {
                          //点击取消按钮
                          DataHelper.setBooleanSF(HomeActivity.this,AppConstant.user_OPEN_NOTICE,false);
                      }else {
                          NoticeisUtils.openPermissionSetting(HomeActivity.this);
                      }
                  }
              }).show();
          }
      }

        startService(new Intent(this, HfLocationService.class));//启动定位服务，保证下一个界面有定位i信息
        ViewGroup group = (ViewGroup) getWindow().getDecorView();
        fullScreenImmersive(group);
//        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                mPresenter.versionCompre();
//            }
//        }, 1000);

        initTabbar();
    }

    /**
     * 全屏显示，隐藏虚拟按钮 * @param view
     */
    private void fullScreenImmersive(View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_FULLSCREEN;
            view.setSystemUiVisibility(uiOptions);
        }
    }

    private void initTabbar() {
        fragments = initFragments();
        AdapterViewPager adapterViewPager = new AdapterViewPager(getSupportFragmentManager(), fragments);
        homeFragmentViewPage.setAdapter(adapterViewPager);
        homeFragmentViewPage.setOffscreenPageLimit(4);
        bottom_bar.setOnBottomBarOnclick(new HomeBottomBar.OnBottomBarClick() {

            @Override
            public void onClickItem(int index) {
                if (index == 2) {
                    // todo 测试临时使用
//                    Intent intent = new Intent(HomeActivity.this, ReleaseRentSeekingSelectionTypeActivity.class);
//                     Intent intent=new Intent(HomeActivity.this, PersonalHomePageActivity.class);
//                     intent.putExtra("userId","521677655146233856");
//                     intent.putExtra("type",0);

                    //跳转到发布模块
//                    ArmsUtils.startActivity(intent);
                }
            }

            @Override
            public void onCenterClick() {
                if (!AppUtil.userIsLogin(HomeActivity.this)) {
                    ArmsUtils.startActivity(UserLoginActivity.class);
                    ArmsUtils.makeText(HomeActivity.this, "请先登录");
                    return;
                }
                Intent intent = new Intent(HomeActivity.this, HousePublishMainActivity.class);
                //跳转到发布模块
                ArmsUtils.startActivity(intent);
//                ArmsUtils.startActivity(HfRechargeCenterActivity.class);
            }
        })
                .onAttach(homeFragmentViewPage)
                .refreshView();
    }

    @Override
    public boolean useFragment() {
        return true;
    }

    private List<Fragment> initFragments() {
        List<Fragment> fragments = new ArrayList<>();
        fragments.add(HomeMainFragment.newInstance());
        fragments.add(HomeFindFragment.newInstance());
        fragments.add(HomeFindFragment.newInstance());
        fragments.add(HfMeFragment.newInstance());
        return fragments;
    }


    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast.makeText(getApplicationContext(),
                    "再按一次退出程序", Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {

            AppManager.getAppManager().appExit();
            finish();
            System.exit(0);
        }
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        loginJpush();
    }

    /**
     * 登录jpush
     */
    public void loginJpush() {
        UserBean userBean = DataHelper.getDeviceData(this, AppConstant.USER_INFO);//获取用户信息
        if (userBean == null || userBean.getUserId() == null || TextUtils.isEmpty(userBean.getUserId())) {
            //如果用户信息为空，认为用户没有绑定主机，显示绑定主机界面，用户点击界面先让用户登录
            return;
        }
        TagAliasOperatorHelper.TagAliasBean tagAliasBean = new TagAliasOperatorHelper.TagAliasBean();

        String alias = userBean.getUserId();
        tagAliasBean.alias = userBean.getUserId();
//        if (TextUtils.isEmpty(preferencesService.getInfoByKey(tagAliasBean.alias)))
//        {
        //判断是不是已经注册到jpush，没有就调用jpush注册登录，如果登录就不做处理
        tagAliasBean.action = ACTION_SET;
        tagAliasBean.isAliasAction = true;
        TagAliasOperatorHelper.getInstance().handleAction(getApplicationContext(), 1, tagAliasBean);
//        }
    }
}
